import {
    Pressable,
    StatusBar,
    StyleSheet,
    Text,
    View,
    ImageBackground,
    Image,
    ScrollView,
    DeviceEventEmitter,
    NativeEventEmitter,
    NativeModules,
} from 'react-native';
import React, { useEffect, useRef } from 'react';
import { useRoute, useNavigation } from '@react-navigation/native';
import Icon from 'react-native-vector-icons/Ionicons';
import LinearGradient from 'react-native-linear-gradient';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { useTranslation } from 'react-i18next';
import { deviceStore, observer, webSocketStore } from '~/store';
import { useTimeout } from '~/common';
import { px2dp, scale, width } from '~/utils/px2dp';
import BoldEcharts from './components/BoldEcharts';
import { isOpenManullyBlood, openBloodData, GetBoldStatus } from '~/utils/ble/application';

const BleManagerModule = NativeModules.BleManager;
const bleManagerEmitter = new NativeEventEmitter(BleManagerModule);
let SECGindex = 0;
let PPGindex = 0;
let dataTimeout: any = null;
let num = 0;
let PPGdata: any = [
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
];
let SECGdata: any = [
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
];

const OpenBlood = observer(() => {
    const { t } = useTranslation();
    const insets = useSafeAreaInsets();
    const router = useRoute<any>();
    const navigation: any = useNavigation();
    const { type, device_sn, subDevice_sn, device_code } = router.params || {};
    const [isTimeout, startTimer, resetTimer] = useTimeout(10); // 获取超时相关
    const { bloodStatus, systolic, diastolic, heartrate, microcirculation } = deviceStore.blood;
    const { linkSubDeviceStatus } = webSocketStore;
    const echartsRef = useRef<any>();
    const SECGRef = useRef<any>();
    const PPGOption = {
        grid: {
            left: '3%',
            top: '0%',
            width: '96%',
            height: 100,
            containLabel: false,
            show: false,
        },
        xAxis: {
            type: 'category',
            data: Array.from({ length: 60 }, (_, i) => i),
            nameLocation: 'center',
            boundaryGap: false,
            show: false,
            axisLine: {
                show: false, // 是否显示坐标轴轴线
                onZero: false,
            },
        },
        yAxis: {
            type: 'value',
            show: false,
            x: 'center',
            max: 255,
            min: 0,
        },
        series: [
            {
                showSymbol: false,
                animation: false,
                data: PPGdata,
                type: 'line',
                smooth: true,
                lineStyle: {
                    color: '#FF4E4E',
                },
            },
        ],
    };

    const SECGOption = {
        grid: {
            left: '3%',
            top: '0%',
            width: '96%',
            height: 100,
            containLabel: false,
            show: false,
        },
        xAxis: {
            type: 'category',
            data: Array.from({ length: 60 }, (_, i) => i),
            show: false,
            boundaryGap: false,
            nameLocation: 'center',
            axisLine: {
                show: false, // 是否显示坐标轴轴线
                onZero: false,
            },
        },
        yAxis: {
            type: 'value',
            show: false,
            x: 'center',
            max: 255,
            min: 0,
        },
        series: [
            {
                showSymbol: false,
                animation: false,
                data: SECGdata,
                type: 'line',
                smooth: true,
                lineStyle: {
                    color: '#FF4E4E',
                },
            },
        ],
    };
    //SECG图表更新
    const SECGupdata = () => {
        try {
            SECGRef.current.setNewOption({
                series: [
                    {
                        data: SECGdata,
                    },
                ],
            });
        } catch (error) {}
    };
    //SECG图表更新
    const PPGupdata = () => {
        try {
            echartsRef.current.setNewOption({
                series: [
                    {
                        data: PPGdata,
                    },
                ],
            });
        } catch (error) {}
    };
    const setEchartsSECGRef = (res: any) => {
        SECGRef.current = res;
    };
    const setEchartsRef = (res?: any) => {
        echartsRef.current = res;
    };

    // 开关血压
    const onPress = () => {
        if (linkSubDeviceStatus == 0 && deviceStore.device.connectedDeviceStatus == 0) {
            Toast.show({ content: t('OpenBlood.t12') });
            return;
        }
        startTimer();
        if (bloodStatus) {
            isOpenManullyBlood(0, router.params);
        } else {
            isOpenManullyBlood(1, router.params);
        }
    };

    const callrealblood = async (res) => {
        try {
            num = 0;
            if (dataTimeout) {
                clearInterval(dataTimeout);
            }
            dataTimeout = await setInterval(async function () {
                if (!bloodStatus) {
                    await PPGupdata();
                    await SECGupdata();
                }
                if (num >= 20) {
                    clearInterval(dataTimeout);
                    return;
                }
                if (num === 0) {
                    if (PPGindex >= 60) {
                        PPGindex = 0;
                    }
                    PPGdata.splice(PPGindex, 2, res.data[num], null);
                    PPGindex++;
                    await PPGupdata();
                } else if (num % 2 == 0) {
                    if (PPGindex >= 60) {
                        PPGindex = 0;
                    }
                    PPGdata.splice(PPGindex, 2, res.data[num], null);
                    PPGindex++;
                    await PPGupdata();
                } else {
                    if (SECGindex >= 60) {
                        SECGindex = 0;
                    }
                    if (res.data[num] > 35) {
                        res.data[num] = 35 * 7;
                    } else {
                        res.data[num] = res.data[num] * 7;
                    }
                    SECGdata.splice(SECGindex, 2, res.data[num], null);
                    SECGindex++;
                    await SECGupdata();
                }
                num += 1;
            }, 33);
        } catch (error) {
            console.log('errorerrorerrorerror', error);
        }
    };
    useEffect(() => {
        clearInterval(dataTimeout);
        const BleEchartsEmitter = DeviceEventEmitter.addListener('BleEchartsEmitter', async (res) => {
            await callrealblood(res);
        });
        const didUpdateValue = bleManagerEmitter.addListener(
            'BleManagerDidUpdateValueForCharacteristic',
            async (data) => {
                if (data.characteristic.toLowerCase() !== '9c2c48aa-69c3-4742-9f69-764351fb0783') {
                    return;
                }
                await callrealblood({ data: data.value });
            },
        );
        return () => {
            didUpdateValue.remove();
            clearInterval(dataTimeout);
            BleEchartsEmitter.remove();
        };
    }, []);

    useEffect(() => {
        if (bloodStatus) {
            GetBoldStatus(router.params);
            setTimeout(() => {
                openBloodData(1, router.params);
            }, 1000);
        }
    }, [bloodStatus]);
    useEffect(() => {
        resetTimer();
    }, [bloodStatus]);

    useEffect(() => {
        if (isTimeout) {
            Toast.show({ content: t('OpenBlood.t13') });
            resetTimer();
            Object.assign(deviceStore.blood, {
                bloodStatus: false,
                systolic: 0,
                diastolic: 0,
                heart: 0,
                microcirculation: 0,
            });
        }
    }, [isTimeout]);
    return (
        <LinearGradient colors={['#F3FCFF', '#DBF9FB']} style={styles.container}>
            <StatusBar translucent={true} backgroundColor={'#F3FCFF'} />
            <View style={[styles.row, styles.between, { marginHorizontal: px2dp(32), marginTop: insets.top }]}>
                <Pressable onPress={() => navigation.goBack()}>
                    <Icon name="chevron-back-outline" size={26} color={'#000'}></Icon>
                </Pressable>
                <Text style={styles.title}>{t('OpenBlood.title')}</Text>
                <View />
            </View>
            <ScrollView contentContainerStyle={styles.contentContainerStyle} showsVerticalScrollIndicator={false}>
                <View>
                    <Text style={styles.echarts_title}>PPG</Text>
                    <ImageBackground
                        style={styles.bg}
                        source={{
                            uri: 'https://bjy-dev.oss-cn-shenzhen.aliyuncs.com/xcx/chartbg.png',
                        }}>
                        <BoldEcharts pieOption={PPGOption} setEchartsRef={setEchartsRef} />
                    </ImageBackground>
                </View>
                <View style={{ marginTop: px2dp(64) }}>
                    <Text style={styles.echarts_title}>SECG</Text>
                    <ImageBackground
                        style={styles.bg}
                        source={{
                            uri: 'https://bjy-dev.oss-cn-shenzhen.aliyuncs.com/xcx/chartbg.png',
                        }}>
                        <BoldEcharts pieOption={SECGOption} setEchartsSECGRef={setEchartsSECGRef} type={1} />
                    </ImageBackground>
                </View>
                <View style={styles.menue}>
                    <View style={[styles.row, styles.between]}>
                        <View>
                            <Text style={styles.numblood}>{systolic > 0 ? systolic : t('OpenBlood.t1')}</Text>
                            <Text style={styles.unit}>mmHg</Text>
                            <Text style={styles.unitzh}>{t('OpenBlood.t2')}</Text>
                        </View>
                        <View>
                            <Text style={styles.numblood}>{diastolic > 0 ? diastolic : t('OpenBlood.t1')}</Text>
                            <Text style={styles.unit}>mmHg</Text>
                            <Text style={styles.unitzh}>{t('OpenBlood.t3')}</Text>
                        </View>
                        <View>
                            <Text style={styles.numblood}>{heartrate > 0 ? heartrate : t('OpenBlood.t1')}</Text>
                            <Text style={styles.unit}>{t('OpenBlood.t4')}</Text>
                            <Text style={styles.unitzh}>{t('OpenBlood.t5')}</Text>
                        </View>
                        <View>
                            <Text style={styles.numblood}>
                                {microcirculation > 0 ? microcirculation : t('OpenBlood.t1')}
                            </Text>
                            <Text style={styles.unit}>{t('OpenBlood.t6')}</Text>
                            <Text style={styles.unitzh}>{t('OpenBlood.t7')}</Text>
                        </View>
                    </View>
                    <Pressable style={styles.btn} onPress={onPress}>
                        <Image
                            style={styles.icons}
                            source={{
                                uri: bloodStatus
                                    ? 'https://bjy-dev.oss-cn-shenzhen.aliyuncs.com/xcx/images/openBtn.png'
                                    : 'https://bjy-dev.oss-cn-shenzhen.aliyuncs.com/xcx/images/closeBtn.png',
                            }}
                        />
                        <Text>{bloodStatus ? t('OpenBlood.t8') : t('OpenBlood.t9')}</Text>
                    </Pressable>
                </View>
            </ScrollView>
        </LinearGradient>
    );
});
export default OpenBlood;
const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    row: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    between: {
        justifyContent: 'space-between',
    },
    title: {
        fontSize: scale(28),
        color: '#000',
        fontWeight: 'bold',
    },
    contentContainerStyle: {
        flexGrow: 1,
        marginTop: '10%',
    },
    bg: {
        width: width,
        height: px2dp(200),
    },
    echarts_title: {
        fontSize: scale(40),
        color: '#000',
        marginLeft: px2dp(32),
        marginBottom: px2dp(24),
    },
    menue: {
        flexGrow: 1,
        backgroundColor: '#fff',
        padding: px2dp(24),
        marginTop: '20%',
    },
    numblood: {
        fontSize: scale(40),
        fontWeight: '400',
        color: '#666666',
        textAlign: 'center',
    },
    unit: {
        color: '#A4A4A4',
        marginVertical: px2dp(8),
        fontSize: scale(22),
        textAlign: 'center',
    },
    unitzh: {
        color: '#111111',
        fontSize: scale(24),
        textAlign: 'center',
    },
    icons: {
        width: px2dp(80),
        height: px2dp(80),
    },
    btn: {
        justifyContent: 'center',
        alignItems: 'center',
        marginTop: '30%',
    },
});
